<!DOCTYPE htm PUBLIC "-//W3C//DTD Xhtm 1.0 Transitional//EN" "DTD/xhtm1-transitional.dtd"> 
<htm xmlns="http://www.w3.org/1999/xhtm" xml:lang="de" lang="de">
<head>
 <meta http-equiv="content-type" content="text/htm; charset=iso-8859-1" />
 <meta http-equiv="content-style-type" content="text/css" />
 <meta name="author" content="Arlsair" />
 <meta name="date" content="2004-01-22" />
 <title>MaskTools</title>
 <link rel="stylesheet" type="text/css" href="../../style.css" />
</head><body>
<h1>MaskTools</h1>

<h2>&Uuml;bersicht</h2>
<b>Autor:</b> Kurosu<br />
<b>Version:</b> 1.4.2<br />
<b>Download:</b> <a href="http://www.avisynth.org/warpenterprises/" target="_blank">http://www.avisynth.org/warpenterprises/</a><br />
<b>Kategorie:</b> Verschiedenes<br />
<b>Anforderungen:</b> YV12 Farbraum<br />
<hr>
<h3>Table of contents
</h3>
<p>
I) Disclaimer (don't skip that part, but I don't force you to learn it either)<br>
II) What it is<br>
   1) Simple version<br>
   2) Description<br>
III) Revisions<br>
IV) Developer's walkthrough<br>
V) Functions description<br>
VI) Some practical uses<br>
   1) MSharpen<br>
   2) MSoften<br>
   3) Rainbow reduction<br>
   4) Supersampled fxtoon<br>
   5) Warpsharp for dark luma<br>
   6) pseudo-deinterlacer (chroma will still be problematic)<br>
   7) Non-rectangular overlays<br>
   8) Replace backgrounds<br>
   9) Kmf-Toon ;-)<br>
VII) TODO
</p>
<h3>I) Disclaimer
</h3>
<p>This plugin is released under the GPL license. You must agree to the terms of
'Copying.txt' before using the plugin or its source code.<br>
<br>
You are also advised to use it in a philanthropic state-of-mind, i.e. not "I'll keep this secret for myself".<br>
<br>
Last but not least, a very little part of all possible uses of each filter was tested (maybe 5% - still a couple of hours spent to debug ;-). Therefore,
feedback is _very_ welcome (the opposite - lack of feedback - is also true...)
</p>
<h3>II) What it is
</h3>
<p>1) Simple version<br>
After a processing, you may need to keep only a part of the output. Say, you have
a clip named smooth that is the result of a smoothing (blur() for instance) on a
clip named source.<br>
Most of the noise from source have disappeared in smooth, but so have details. You could therefore want to only keep filtered pixels and discard those where
there are big difference of color or brightness. That's what does MSmooth by D. Graft for instance. Now consider that you write on an image pixels from smooth
that you want to keep as white pixels, and the other ones from source as black pixels. You get what is called a mask. MaskTools deals with the creation, the
enhancement and the manipulating of such mask for each component of the YV12 colorspace.<br>
<br>
2) Description<br>
This Avisynth 2.5 YV12-only plugin offers several functions manipulating clips as masks:<br>
- EdgeMask will build a mask of the edges of a clip, applying thresholdings (proper values will enable or disable them).<br>
- Inflate will 'inflate' the high values in a plane, by putting in the output plane either the average of the 8 neighbours if it's higher than the
original value, otherwise the original value. The opposite function is called Deflate (dedicated to Phil Katz).<br>
- Expand will 'expand' the high values in a plane, by putting in the output the maximum value in the 3x3 neighbourhood around the input pixel. The
opposite function is called Inpand.<br>
- Invert will invert the pixel (i.e. out = 255 - in); this can be also used to apply a 'solarize' effect to the picture<br>
- Binarize will binarize the input picture depending on a threshold and a command.<br>
- YV12Substract is the same as Subtract, also works in YV12, but *should* be a bit faster (because MMX optimised).<br>
- YV12Layer is the equivalent of most of original Layer's operations, but in YV12; alpha channel isn't exploited, so it might or might not fill the same
purpose.<br>
- Logic will perform most typical logical operations (in fact, the ones provided by MMX mnemonics, though C functions are still available, mainly
because of the picture dimensions limits).<br>
- FitY2UV/FitY2U/FitY2V resizes Y plane and replace UV/U/V plane(s) by the result of the resize (you can specify your resizer filter, even one that
isn't built-in AviSynth); the opposite  functions are FitU2Y and FitV2Y Fast&lt;Function> is the "fast" version (ie home-made) resizing only one
plane.<br>
- OverlayMask will compare 2 clips based on luminance and chrominance thresholds, and output whether pixels are close or not (close to what
ColorKeyMask does).<br>
- MaskedMerge will take 3 clips and apply a weighed merge between first and second clips depending on the mask represented by clip3.<br>
<br>
In addition, all functions take 3 parameters: Y, U and V (except the FitPlane functions, where obviously the name tells what is processed). Depending on
their value, different operations are applied to each plane:<br>
- value=3 will do the actual process of the filter,<br>
- value=2 will copy the 2nd video plane (if appliable) to the output corresponding plane<br>
- value=1 will not process it (i.e., most often, left it with 1st clip plane or garbage - check by yourself)<br>
- value=[-255...0] will fill the output plane with -value (i.e. to have grey levels, use U=128,V=128)<br>
<br>
A last point is the ability of some functions to process only a part of the frame:<br>
- this behaviour is set by the parameters (offX, offY) (position of the start point) and (w,h) (width and height of the processed area); filters should
modify those parameters so that the processed area is inside the 2 pictures<br>
- in case of a filter (except YV12Layer) using 2 clips, the 2 clips must have the same dimensions<br>
- in all cases, the picture must be at least MOD8 (MOD16 sometimes) in order to enable the filter to use MMX functions (ie work at full speed)<br>
<br>
This was intended for modularity and atomic operations (or as useful as possible), not really speed. It became both bloated and slow. I let you
decide whether this statement is totally true, or a bit less... The examples of VI) are most probably much faster applied with the original filters.
</p>
<h3>III) Revisions
</h3>
<p>1.4.1<br>
- Fixed the dreadly bug "multiple instances of a filter with different functions needed"
</p>
<p>1.4.0<br>
- Added an experimental LUT filter. Not tested, debug later.
</p>
<p>1.3.0 (private version)<br>
- Made usable the FitPlane function (still an overload of work when only one plane has to be resized) which was previously undocumented;
therefore, added FastFitPlane functions (corresponding FitPlane ones should be useless now, except for the resizers settings)<br>
- Allowed the specification of a processing area for many filters; however, this should not produce any noticable speed increase.<br>
- Cleaned YV12Layer (in particular the unusable "Darken"/"Lighten" modes)<br>
- Added OverlayMask, a function that compares 2 clips, and outputs a mask of the parts that are identical (slow and far from perfect).
</p>
<p>1.2.0 (private version)<br>
- YV12Layer: no more useless RGB32 conversion! Approximately the same as Arithmetic (except a third clip is not used), so that one is gone...<br>
- YV12Substract: hey, why only a C version? Masks are really an underused feature of AviSynth |-[
</p>
<p>1.1.0 (private version)<br>
- Older inflate/deflate are renamed expand/inpand while newer functions replace them<br>
- Logic and Arithmetic functions added (shouldn't produce the expected results because of no debugging)<br>
- Edgemask now takes 4 thresholds (2 for luma and 2 for chroma). They are used for:<br>
  . setting to 0 or leaving as is a value depending on first threshold,<br>
  . setting to 255 or leaving as is a value depending on the second one.
</p>
<p>1.0.2 (last version - public project dropped):<br>
- Fix the shift for edgemask using sobel and roberts (misplaced MMX instruction)<br>
- MaskMerge now works (mask cleared before being used... check with MaskMerge(clip3,clip3) for instance)
</p>
<p>1.0.1: Initial release
</p>
<h3>IV) Developer's walkthrough
</h3>
<p>Skip to V) if you're not interested in developing the tools available.<br>
<br>
The project is a VC++ 6 basic project. Each filter has its own folder which stores the header used by the interface, the source for the function
members, the source for processing functions and its header. Let's look at EdgeMask:<br>
- EdgeMask.h is included by the interface to know what the filter 'looks like' (but interface.cpp still holds the definition of the
calling conventions and exported functions)<br>
- EM_func.h describes the different processing functions (they should all have the same prototype/parameters):<br>
  . Line_MMX and Line_C<br>
  . Roberts_MMX and Roberts_C<br>
  . Sobel_MMX and Sobel_C<br>
- EM_func.cpp, as all &lt;filter's initials>_func.cpp, stores the implementation of the processing functions, and sometimes their MMX
equivalents.<br>
- EdgeMask.cpp implements the class; the constructor select the appropriate processing function (MMX? C? Roberts? Line? Sobel?) and uses
it to fill the generic protected function pointer used in GetFrame<br>
<br>
Interface.cpp stores the export function and all of the calling functions (AVSValue ... Create_&lt;filter>).<br>
<br>
ChannelMode.cpp defines the Channel operating modes. There could be added the equivalent of a debugprintf.<br>
<br>
This quick walkthrough won't probably help most developers, as the examples of V) for users, but that's the best I've come with so far. It will improve
of course over time depending on the success of the idea, which main drawback, speed, will probably make it scarcely used, if ever. &lt;g>
</p>
<h3>V) Functions description (Y,U,V parameters described above)
</h3>
<p>1) EdgeMask(th1=[0..255], th2=[0..255], string):<br>
Component is either Y, U or V; derivative is the result of the convolution by the differential kernel. MMX code is only used with MOD8 width (might
not be necessary).<br>
- string: which differential convolution to use:<br>
  . "line" will try to spot darker thin (1 pixel-wide) lines in the picture (it has an incorporated anti-noise floor which makes it ignore
any variation lower than 3)<br>
  . "roberts" will apply a pseudo-Roberts 2x2 kernel:<br>
    2 -1<br>
    -1 0<br>
  . "sobel" will apply a pseudo-Sobel 3x3 kernel:<br>
     0 -1 0<br>
    -1  0 1<br>
     0  1 0<br>
  . "hq" uses a Laplacian kernel:<br>
    -1 -1 -1<br>
    -1  8 -1<br>
    -1 -1 -1<br>
  . "special" uses this kernel:<br>
    -1/4 0 -1/4<br>
      0  1  0<br>
    -1/4 0 -1/4<br>
  . "cartoon" uses the pseudo-Sobel kernel but only keeps components with lower value than their neighbours (i.e. negative values of the
derivative)<br>
- th1: threshold under which component value is set to 0<br>
- th2: threshold under which component value is set to the derivative value, and above which it's set to 255<br>
<br>
2) Inflate/Deflate(int offX, int offX, int w, int h)<br>
(works in-place, so unprocessed planes contain the original data of the first clip)
Replace the component value by the maximum (respectively minimum) in the 9 pixels of a 3x3 neighbourhood.
The 4 parameters specify the area to process, as for all other plugins with such options. By default, the whole pciture is processed.<br>
<br>
3) Inpand/Expand(int offX, int offX, int w, int h) (works in-place)<br>
Replace the component value by the average of the values of its 8 neighbours if it is respectively lower or higher than the original value.<br>
<br>
4) Invert(int offX, int offX, int w, int h) (works in-place)<br>
Replace pixel's value by 255-pixel's value Binarize(upper=false) could be seen (but isn't processed as) as&nbsp;Invert().Binarize(upper=true)<br>
<br>
5) Binarize(threshold=[0..255], upper=true/false, int offX, int offX, int w, int
h) (works in-place)<br>
- threshold is the limit to tell when to put 0 or 255<br>
- upper = true will replace values higher than threshold by 0 and lower or equal by 255 upper = false simply does the opposite<br>
- Nota: in YV12, the luma range is 16-235 (yay! I like limitations due to some analogical crap - doesn't matter much, but still a pain to care
for), so don't be surprised, and set some of your levels to 17...<br>
<br>
5) input.MaskedMerge(clip clip2, clip clip3, int offX, int offX, int w, int h) (works in-place, mode=2 will copy the plane of clip2 to clip1)<br>
   output = [(255-clip3)*input + clip3*clip2]/256<br>
   Therefore, it isn't perfectly weighed/normalized, but will still do the job. One could see as a simple (no alpha considered) layer("add")<br>
<br>
6) YV12Subtract(clip clip1, clip clip2, int tolerance, int offX, int offX, int w, int h) (works in-place, mode=2 will copy the plane of clip2 to clip1)<br>
   Performs exactly the same as Subtract, but uses MMX.<br>
   - if mode&lt;0:<br>
     if clip1 &lt; clip2, output = 255 + clip1 - clip2<br>
     else output = clip1 - clip2<br>
   - otherwise<br>
     output' = |clip2 - clip1| - tol<br>
     if output'&lt;0, output = output'<br>
     else output = output'<br>
   The last mode can be used in many cases to only process pixels that are different from an image (MaskOverlay would be nicer, though)<br>
<br>
7) YV12Layer(clip clip1, clip clip2, string operator, int level, bool chroma, int offX, int offX, int w, int h)<br>
   Same as Layer, except "Lighten" and "Darken" were removed (the luma of the 2nd clip gaves the weighing for each luminance, but should be reused
for chrominance, not practical in current architecture).<br>
<br>
8) FitPlane(string resizer) has the following incarnations:<br>
   - luma to chroma: FitY2U, FitY2V, FitY2UV<br>
   - chroma to luma: FitU2Y, FitV2Y<br>
   - chroma to chroma: FitU2V, FitV2U<br>
   You can by this mean propagate a mask created on a particular plane to another plane.<br>
<br>
9) FastFitPlane: it has the same incarnations as FitPlane, but use its own resizer (could replace AviSynth's C ReduceBy2 ;-)<br>
<br>
10) MaskOverlayclip clip1, clip clip2, luma threshold tY, chroma threshold tC, int strictness)<br>
   If: U and V values of a group of 4 pixels of clip1 (due to the YV12's 4:2:0 sampling) is different by less than tC from clip2's
corresponding pixel's chroma.&nbsp;<br>
   Then: if more than strictness pixels out of those 4 pixels have a luma different from the corresponding pixels' luma by less than tY.<br>
Then: mark the pixel satisfying to the 2 above conditions as (255,255,255) (process mask = full for maskedmerge)
</p>
<h3>VI) Some practical uses (not tested extensively)
</h3>
<p>Those won't produce the exact same results as the original filters they try to mimic, in addition to be far more slower. Despite the numerous additional
functions, no newer idea.<br>
<br>
Notes:&nbsp;<br>
- I'm too lazy to update the syntax, especially regarding how mode=2 works, and how EdgeMask was updated (now longer needs of a Binarize for instance)<br>
- Some filters I describe as 'to create' already exist (imagereader, levels for clamping, ...).<br>
<br>
1) MSharpen<br>
. Build EdgeMask of clip1, Binarize it and store the result into clip3<br>
. Apply any sharpening filter to clip1 and store it into clip2<br>
. return MaskMerge(clip1,clip2,clip3):<br>
The sharpened edges of clip2 higher than the threshold given to Binarize will be sharpened and used to replace their original value in clip1.
You could also write a filter with a particular Look-up table (best would look like a bell), replace Binarize by it, and have a weighed sharpening
depending on the edge value: that's the HiQ part in SmartSmoothHiQ<br>
<br>
clip2 = clip1.&lt;EdgeEnhancer>(&lt;parameters>)<br>
#U and V planes don't need filtering, Y needs it<br>
#EdgeMask(&lt;...>,"roberts",Y=3,U=-128,V=-128) for greyscale map<br>
clip3 = clip1.EdgeMask(15,60,"roberts",Y=3,U=1,V=1)<br>
return MaskedMerge(clip1,clip2,clip3)<br>
<br>
2) MSoften<br>
Replace EdgeEnhancer by a spatial softener (cascaded blurs? spatialsoftenMMX?) and use upper=true to select near-flat pixels.<br>
<br>
3) Rainbow reduction (as described here: http://forum.doom9.org/showthread.php?s=&amp;threadid=48167)<br>
Warning, this isn't a miracle solution either<br>
clip2 = clip1 soften at maximum (using deen("m2d") or edeen for instance)<br>
#Get luma edgemap and increase edges by inflating<br>
# -> wider areas to be processed<br>
clip3 = clip1.EdgeMask(6,"roberts",Y=3,U=1,V=1).Inflate(Y=3,U=1,V=1)<br>
#Now, use the luma edgemask as a chroma mask<br>
clip3 = YtoUV(clip3,clip3).reduceby2().Binarize(15,upper=false,Y=1,U=3,V=3)<br>
#We have to process pixels' chroma near edges, but keep intact Y plane<br>
return MaskedMerge(clip1,clip2,clip3,Y=1,U=3,V=3)<br>
<br>
4) Supersampled fxtoon<br>
Not tested<br>
. Use tweak to darken picture or make a plugin that scales down Y values -> clip2<br>
. Build edge mask, Supersample this mask, Binarize it with a high threshold (clamping sounds better), Inflate it -> clip3<br>
. Apply the darker pixels of clip2 depending on the values of clip3<br>
<br>
5) Warpsharp for dark luma<br>
Not tested<br>
. Apply warpsharp -> clip2 (replacement pixels)<br>
. Create a clamping filter or a low-luma bypass filter -> clip3 (mask)<br>
<br>
6) pseudo-deinterlacer (chroma will still be problematic)<br>
Not tested<br>
. clip2 = clip1.SeparateFields().SelectEven().&lt;Method>Resize(&lt;parameters>)<br>
. clip3 = clip1.&lt;CombingDetector>(&lt;parameters>)<br>
. return MaskedMerge(clip1,clip2,clip3,Y=3,U=3,V=3)<br>
 (chroma even more problematic)<br>
<br>
7) Non-rectangular overlays<br>
In fact, this is handled more nicely by layer and mask...<br>
#Simple hack because ImageReader needs an integer fps...<br>
#Most sources are natively in YUY2/YV12<br>
clip = avisource("test.avi").ConvertToYV12().assumefps(fps)<br>
#Load the picture to be overlayed<br>
image = ImageReader("mask.bmp",0,clip.framecount()-1,24,use_DevIl=false)<br>
#Simple way: assume black is transparent&nbsp;<br>
#Any other colour would be quite more complicated*<br>
masktemp=imageYV12.Binarize(17,upper=false,Y=3)<br>
#We set the luma mask to fit the chroma planes<br>
mask=mask.FitY2UV()<br>
#Now that we have the mask that tells us what we want to keep...<br>
#Replace by image the parts of clip masked by mask!<br>
maskedmerge(clip,image,mask,Y=3,U=3,V=3)<br>
#*solution: mask=OverlayMask(image,image.BlankClip("$xxxxxx"),1,1)<br>
<br>
8) Replace backgrounds<br>
This example clearly would look better in RGB. To avoid typical problems due to noise or compression, you would better use blurred versions of the clip
and picture.<br>
source=avisource("overlay.avi").assumefps(24)<br>
#blur the source<br>
clip=source.blur(1.58).blur(1.58).blur(1.58)<br>
#load the background to replace, captured from the blurred sequence<br>
bgnd=ImageReader("bgnd.ebmp",0,clip.framecount()-1,24,use_DevIl=false)<br>
#load new background<br>
new=ImageReader("new.ebmp",0,clip.framecount()-1,24,use_DevIl=false)<br>
#integrated filter to output the mask = (clip~overlay?)<br>
mask=OverlayMask(clip,overlay.ConvertToYV12(),10,10)<br>
MaskedMerge(source,new.ConvertToYV12()s,mask,Y=3,U=3,V=3)<br>
<br>
9) K-mfToon<br>
I need to include more info (original urls/posts) but for now I think mfToon's original author, mf (mf@onthanet.net) will not react too
violently to it, while it's still not addressed.<br>
The output of the function inside K-mfToon.avs should be identical to the output of the original mftoon.avs (also included), with twice the speed.<br>
The requirements are:<br>
- For mfToon:<br>
  . load the plugins called "MaskTools", "warsharp", "awarsharp"&nbsp;
</p>
<h3>VII) TODO
</h3>
<p>Nothing, it all depends in feeback<br>
</p>
</body>
</html>
